<template>
  <div class="page-common-layout">
    <div class="page-common-left" style="width:15%;padding: 0">
      <TableClassify
        :title="classifyTitle"
        :treeData="classifyData"
        @select="masterRowClick"
        :replaceFields="{
          title: 'classificationName',
          key: 'classificationCode',
        }"
        :loading="masterConfirmLoading"
        searchPlaceholder="请输入报表分类"
        searchFieldName="classificationName"
      ></TableClassify>
    </div>
    <div class="page-common-content">
      <tool-bar
        @search="$refs.subList.refresh(true)"
        @reset="
          () => {
            (subQueryParam = masterListCode
              ? {
                  code: masterListCode,
                }
              : {}),
              $refs.subList.refresh(true);
          }
        "
      >
        <template slot="toolForm">
          <a-form-item label="报表名称">
            <a-input
              v-model="subQueryParam.dataReportName"
              placeholder="请输入报表名称"
            />
          </a-form-item>
          <a-form-item label="报表编码">
            <a-input
              v-model="subQueryParam.dataReportCode"
              placeholder="请输入报表编码"
            />
          </a-form-item>
        </template>
        <template slot="toolBtn">
          <a-button
            class="cu-btn-primary"
            icon="plus"
            @click="openCardSelection('add')"
            >{{ $ct("newReport", "新建报表") }}
          </a-button>
          <a-button type="link" icon="upload" @click="importReportFile"
            >{{ $ct("Import", "导入") }}
          </a-button>
        </template>
      </tool-bar>
      <DataGrid
        ref="subList"
        type="sub"
        :url="url"
        :columns="subColumns"
        :queryParam="subQueryParam"
        rowKey="uuid"
        showPagination="auto"
        :showRowSelect="false"
        :scroll="{ x: 1300 }"
      >
        <span slot="renderDataReportName" slot-scope="{ text, record, index }">
          {{ text | nameFilter }}
        </span>
        <span slot="renderCreator" slot-scope="{ text, record, index }">
          {{ record.creator }}/{{ record.creatorId }}
        </span>
        <span slot="renderModifier" slot-scope="{ text, record, index }">
          {{ record.modifier }}/{{ record.modifierId }}
        </span>
        <template slot="renderAction" slot-scope="{ text, record }">
          <a @click="designReport(record)">编辑</a>
          <span class="action-margin"></span>
          <a @click="handleDelSub(record)" class="action-delete">{{
            $ct("delete", "删除")
          }}</a>
          <span class="action-margin"></span>
          <a-dropdown>
            <a class="ant-dropdown-link">
              {{ $ct("more", "更多") }}
              <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="openCardSelection('preview', record)">
                  {{ $ct("previewReport", "预览报表") }}</a
                >
              </a-menu-item>
              <a-menu-item>
                <a @click="reportCopy(record)">{{
                  $ct("copyReport", "复制报表")
                }}</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleRelease(record)">{{
                  $ct("bindMenu", "绑定菜单")
                }}</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="openCardSelection('export', record)">{{
                  $ct("exportFile", "导出文件")
                }}</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </DataGrid>
      <card-selection
        ref="subModal"
        :visible="cardVisible"
        :type="cardType"
        @click="openPage"
        @cancel="() => (cardVisible = false)"
        :title="cardTitle"
        :width="cardWidth"
      />
      <template-form
        ref="templateForm"
        :key="timeString"
        :visible.sync="templateVisible"
      />
      <!-- 绑定菜单 -->
      <release-modal
        ref="releaseModal"
        @ok="handleReleaseOk()"
        :visible.sync="visibleRelease"
        :loading="releaseConfirmLoading"
        :mdl="subListMdl"
      ></release-modal>
      <!-- 上传文件 -->
      <web-upload
        ref="webUploadModal"
        :visible="visibleFile"
        :showTipText="true"
        :width="450"
        url="/report/templet/importReportJson"
        @cancel="() => (visibleFile = false)"
        @ok="importReportJson"
      />
      <!--二维码-->
      <a-modal
        title="扫码预览"
        :visible="qrVisible"
        :width="330"
        :footer="null"
        @cancel="(e) => (qrVisible = false)"
      >
        <vue-qr :text="qrValue" :size="300" :correctLevel="3"></vue-qr>
        <div class="text-center text-xs padding-xs">使用app扫码预览</div>
      </a-modal>
    </div>
  </div>
</template>

<script>
import { masterTableMixin } from "@/mixins/masterTableMixin";
import { DataGrid, TableClassify } from "@/components";
import { getToken } from "@/utils/TopVUI";
import { baseUrl } from "@/services/baseUrl.js";
import cardSelection from "./cardSelection.vue";
import templateForm from "./templates.vue";
import releaseModal from "./releaseModal.vue";
import vueQr from "vue-qr";

export default {
  name: "templet",
  components: {
    DataGrid,
    cardSelection,
    templateForm,
    releaseModal,
    vueQr,
    TableClassify,
  },
  mixins: [masterTableMixin],
  data() {
    return {
      timeString: Date.now().valueOf(),
      masterColumns: [
        {
          title: "分类名称",
          dataIndex: "classificationName",
          ellipsis: true,
        },
      ],
      subColumns: [
        {
          title: "报表名称",
          dataIndex: "dataReportName",
          width: 240,
          scopedSlots: {
            customRender: "renderDataReportName",
          },
        },
        {
          title: "报表编码",
          dataIndex: "dataReportCode",
          width: 80,
        },
        {
          title: "所属分类",
          dataIndex: "classificationName",
          langCode: "className2",
          width: 100,
        },
        {
          title: "创建人",
          dataIndex: "creator",
          langCode: "createdBy",
          scopedSlots: {
            customRender: "renderCreator",
          },
          width: 180,
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          width: 180,
        },
        {
          title: "修改人",
          dataIndex: "modifier",
          scopedSlots: {
            customRender: "renderModifier",
          },
          width: 180,
        },
        {
          title: "修改时间",
          dataIndex: "modifyTime",
          width: 180,
        },
        {
          title: "排序",
          dataIndex: "dataReportSort",
          width: 50,
          align: "center",
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          fixed: "right",
          scopedSlots: {
            customRender: "renderAction",
          },
        },
      ],
      masterQueryParam: {},
      subQueryParam: {},
      url: {
        masterList: "/report/reportClassification/selectAll",
        subList: "/report/templet/getPageSet",
        subSave: "/report/templet/save",
        subUpdate: "/report/templet/update",
        subDelete: "/report/templet/deleteBatch",
      },
      token: "",
      cardVisible: false,
      parameter: {
        father: {
          levelId: 1,
        },
        children: {},
      },
      templateVisible: false,
      masterListCode: "",
      cardType: "",
      visibleRelease: false,
      releaseConfirmLoading: false,
      subListMdl: null,
      visibleFile: false,
      cardTitle: "", //卡片标题
      cardWidth: 0, //卡片宽度
      qrValue: "",
      qrVisible: false,
      masterConfirmLoading: false,
      classifyData: [],
      classifyTitle: "报表分类",
    };
  },
  created() {
    this.getClassifyData();
  },
  mounted() {
    this.token = getToken();
  },
  filters: {
    nameFilter(val) {
      if (val) {
        return val.replace(".ureport.xml", "");
      }
      return val;
    },
  },
  methods: {
    //分类行点击
    masterRowClick(e) {
      this.subQueryParam["code"] = e[0];
      this.masterListCode = e[0];
      this.$refs.subList.rows = null;
      this.$refs.subList.refresh();
    },
    //获取报表分类
    getClassifyData() {
      this.masterConfirmLoading = true;
      this.$post(this.url.masterList, {}).then((res) => {
        if (res) {
          this.classifyData = res;
          this.masterSearchData = res;
          this.masterConfirmLoading = false;
        }
      });
    },
    handleAddReport() {
      window.open(
        baseUrl + "/report/ureport/designer?token=" + this.token,
        "_blank"
      );
    },
    designReport(record) {
      let { dataReportName } = record;
      let userInfo = JSON.parse(localStorage.getItem("USER_INFO") ?? "{}");
      let code = this.$store.state.user.CURRENT_PROJECT_CODE;
      window.open(
        `${baseUrl}/report/ureport/designer?_u=mysql-${dataReportName}&uid=${Base64.encode(
          userInfo.userNameId
        )}&tenantCode=${code}`,
        "_blank"
      );
      //   window.open(
      //     baseUrl +
      //       "/report/ureport/designer?_u=mysql-" +
      //       record.dataReportName +
      //       "&token=" +
      //       this.token,
      //     "_blank"
      //   );
    },
    showReport(record) {
      window.open(
        baseUrl +
          "/report/ureport/pdf/show?_u=mysql-" +
          record.dataReportName +
          "&token=" +
          this.token,
        "_blank"
      );
    },
    paginationPreview(record) {
      window.open(
        baseUrl +
          "/report/ureport/preview?_u=mysql-" +
          record.dataReportName +
          "&token=" +
          this.token,
        "_blank"
      );
    },
    //绑定菜单
    handleRelease(record) {
      const form = this.$refs.releaseModal.form;
      form.resetFields(); // 清理表单数据（可不做）
      this.visibleRelease = true;
      record.dataReportName = record.dataReportName.replace(".ureport.xml", "");
      this.subListMdl = record;
      this.$refs.releaseModal.menuName = record.dataReportName;
    },
    handleReleaseOk() {
      this.releaseConfirmLoading = true;
      const form = this.$refs.releaseModal.form;
      form.validateFields((errors, values) => {
        if (!errors) {
          this.$post("/system/menu/reportBindingMenu", values)
            .then((res) => {
              if (res.statusCode === 200) {
                this.$message.success(res.message, 1.5);
                this.visibleRelease = false;
              } else {
                this.$message.error(res.message, 1.5);
              }
            })
            .finally(() => {
              this.releaseConfirmLoading = false;
            });
        } else {
          this.releaseConfirmLoading = false;
        }
      });
    },
    exportPDF() {
      window.location.href =
        baseUrl +
        "/report/ureport/pdf?_u=mysql-" +
        this.subListMdl.dataReportName +
        "&_n=" +
        this.subListMdl.dataReportName +
        "&token=" +
        this.token;
    },
    exportWord() {
      window.location.href =
        baseUrl +
        "/report/ureport/word?_u=mysql-" +
        this.subListMdl.dataReportName +
        "&token=" +
        this.token;
    },
    exportExcel() {
      window.location.href =
        baseUrl +
        "/report/ureport/excel?_u=mysql-" +
        this.subListMdl.dataReportName +
        "&token=" +
        this.token;
    },
    exportJSON() {
      window.location.href =
        baseUrl +
        "/report/templet/exportReportJson?_u=mysql-" +
        this.subListMdl.dataReportName +
        "&uuid=" +
        this.subListMdl.uuid +
        "&token=" +
        this.token;
    },
    exportExcelPage(record) {
      window.location.href =
        baseUrl +
        "/report/ureport/excel/paging?_u=mysql-" +
        record.dataReportName +
        "&token=" +
        this.token;
    },
    exportExcelPageSheet(record) {
      window.location.href =
        baseUrl +
        "/report/ureport/excel/sheet?_u=mysql-" +
        record.dataReportName +
        "&token=" +
        this.token;
    },
    // 新增
    openCardSelection(type, record) {
      if (type === "export") {
        this.cardWidth = 820;
        this.cardTitle = this.$ct("exportFile", "导出文件");
      } else if (type === "preview") {
        this.cardWidth = 470;
        this.cardTitle = this.$ct("SelectPreviewType", "选择预览类型");
      } else {
        this.cardWidth = 470;
        this.cardTitle = this.$ct(
          "selectReportTypeToCreate",
          "选择创建报表类型"
        );
      }
      this.cardType = type;
      this.cardVisible = true;
      this.subListMdl = record;
    },
    importReportJson() {
      this.visibleFile = false;
      this.$refs.subList.refresh(true);
    },
    handleDelSub(record, type) {
      if (!record || record.length === 0) {
        this.$message.warn("请先勾选需要删除的数据", 1.5);
        return false;
      }
      const that = this;
      let tableName = [],
        uuid;
      if (type == "all") {
        uuid = record.toString();
        that.$refs.subList.selectedRows.forEach((res) => {
          tableName.push(res.tableName);
        });
      } else {
        uuid = record.uuid;
        tableName = record.tableName;
      }
      that.$confirm({
        title: "警告",
        content: "删除后引用该组件的所有功能均受影响，请谨慎删除！",
        okText: "确定",
        cancelText: "取消",
        closable: true,
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          // 在这里调用删除接口
          that
            .$post(that.url.subDelete, {
              uuid: uuid,
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                that.$refs.subList.refresh();
              } else {
                that.$message.error(res.message);
              }
            });
        },
        onCancel() {},
      });
    },
    reportCopy(record) {
      if (!record || record.length === 0) {
        this.$message.warn("请先选择要复制的报表！！！", 1.5);
        return false;
      }
      const that = this;

      that.$confirm({
        title: "操作提示",
        content: `确定要复制该报表吗?`,
        okText: "确定",
        cancelText: "取消",
        closable: true,
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          // 在这里调用删除接口
          that
            .$post("/report/templet/reportCopy", {
              uuid: record.uuid,
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("复制成功！！！", 1.5);
                that.$refs.subList.refresh();
              } else {
                that.$message.error(res.message);
              }
            });
        },
        onCancel() {},
      });
    },
    openPage(key) {
      if ("normalReport" === key) {
        let code = this.$store.state.user.CURRENT_PROJECT_CODE;
        let userInfo = JSON.parse(localStorage.getItem("USER_INFO") ?? "{}");
        window.open(
          `${baseUrl}/report/ureport/designer?uid=${Base64.encode(
            userInfo.userNameId
          )}&tenantCode=${code}`,
          "_blank"
        );
        // window.open(
        //   baseUrl +
        //     "/report/ureport/designer?token=" +
        //     this.token +
        //     "&tenantCode=" +
        //     code,
        //   "_blank"
        // );
      } else if ("createTemplate" === key) {
        this.$refs.templateForm.getAllListData();
        this.templateVisible = true;
      } else if ("exportPDF" === key) {
        this.exportPDF();
      } else if ("exportWord" === key) {
        this.exportWord();
      } else if ("exportExcel" === key) {
        this.exportExcel();
      } else if ("exportJSON" === key) {
        this.exportJSON();
      } else if ("menu" === key) {
        //内页预览
        this.$router.push({
          path: "/report/preview",
          query: {
            url:
              baseUrl +
              "/report/ureport/preview?_u=mysql-" +
              this.subListMdl.dataReportName,
          },
        });
      } else if ("newWindow" === key) {
        //新窗口预览
        window.open(
          baseUrl +
            "/report/ureport/preview?_u=mysql-" +
            this.subListMdl.dataReportName,
          "_blank"
        );

        // window.open(
        //   baseUrl +
        //     "/report/ureport/preview?_u=mysql-" +
        //     this.subListMdl.dataReportName +
        //     "&token=" +
        //     this.token,
        //   "_blank"
        // );
      } else if ("code" === key) {
        //扫码预览
        this.qrValue =
          baseUrl +
          "/report/ureport/preview?_u=mysql-" +
          this.subListMdl.dataReportName +
          "&token=" +
          this.token;
        this.qrVisible = true;
      }
      this.cardVisible = false;
    },
    bindMenu(record) {},
    importReportFile() {
      this.$refs.webUploadModal.add();
      this.visibleFile = true;
    },
  },
};
</script>

<style scoped lang="less">
.page-common-layout .page-common-left + .page-common-content {
  max-width: unset !important;
}
/deep/ .ant-table-small > .ant-table-content .ant-table-header {
  background: #fafafa !important;
}
</style>
